package com.zzchangfu.config;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.mcp.client.McpClient;
import org.springframework.ai.mcp.client.McpSyncClient;
import org.springframework.ai.mcp.client.stdio.ServerParameters;
import org.springframework.ai.mcp.client.stdio.StdioClientTransport;
import org.springframework.ai.mcp.spring.McpFunctionCallback;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * @program: spring-ai
 * @description:
 * @author: liuChangFu
 * @data: 2025-05-12 14:49
 **/
@Component
public class McpConfig {

    @Bean
    public List<McpFunctionCallback> functionCallbacks(McpSyncClient mcpClient) {

        return mcpClient.listTools(null)
                .tools()
                .stream()
                .map(tool -> new McpFunctionCallback(mcpClient, tool))
                .toList();
    }

    @Bean(destroyMethod = "close")
    public McpSyncClient mysqlMcpClient() {
        Map<String, String> env = Map.of(
                "MYSQL_HOST", "host",
                "MYSQL_PORT", "3306",
                "MYSQL_USER", "user",
                "MYSQL_PASSWORD", "password",
                "MYSQL_DATABASE", "database");
        var stdioParams = ServerParameters.builder("D:\\develop\\nodejs\\npx.cmd")
                .args("mysql-mcp-server")
                .env(env)
                .build();
//        System.out.println("Command: " + stdioParams.getCommand() + " " + String.join(" ", stdioParams.getArgs()));
        var mcpClient = McpClient.using(new StdioClientTransport(stdioParams))
                .requestTimeout(Duration.ofSeconds(10000)).sync();
        var init = mcpClient.initialize();
//        System.out.println("MySQL MCP Initialized: " + init);
        return mcpClient;
    }

    @Bean
    public ChatClient chatClient(ChatClient.Builder chatClientBuilder,
                                 List<McpFunctionCallback> functionCallbacks) {
        return chatClientBuilder
                .defaultTools(functionCallbacks.toArray(McpFunctionCallback[]::new))
                .build();
    }
}
